<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateMenuAPIRequest;
use App\Http\Requests\API\UpdateMenuAPIRequest;
use App\Models\Menu;
use App\Repositories\MenuRepository;
use App\Repositories\RoleRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Illuminate\Support\Facades\Auth;


/**
 * Class MenuController
 * @package App\Http\Controllers\API
 */
class MenuAPIController extends AppBaseController
{
    /** @var  MenuRepository */
    private $menuRepository;
    private $roleRepository;
    private $menu_type = [0=>'菜单',1=>'按钮'];

    public function __construct(MenuRepository $menuRepo,RoleRepository $roleRepo)
    {
        $this->menuRepository = $menuRepo;
        $this->roleRepository = $roleRepo;
    }

    /**
     * Display a listing of the Menu.
     * GET|HEAD /menus
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $name = $request->input('name');
        $user = Auth::user();
        $roles = $user->roles;
        $roles = obj2arr($roles);
        $roleArr = array_column($roles,'id','name');
        if(array_key_exists(env('ROOT_KEY'),$roleArr)){
            $menus = $this->menuRepository;
            if($name){
                $menus->findWhere([['name','like',"%{$name}%"]]);
            }
            $menus = $menus->scopeQuery(function($query){
                return $query->orderBy('sort','asc');
            })->all();
        } else {
            $menus = DB::table("menu")
                ->leftjoin("role_has_menu", "role_has_menu.menu_id",'=','menu.id')
                ->whereIn("role_has_menu.role_id",$roleArr);
            if ($name) {
                $menus = Menu::where("name", "like", "%{$name}%");
            }
            $menus = $menus->orderBy("sort",'asc')->get();
        }
        $menus = obj2arr($menus);
        $menus = make_tree($menus, 'id', 'pid', '_child', 0);
        return $this->sendResponse($menus, '查询成功');
    }

    /**
     * Display menu listing
     * GET /menus
     *
     * @param Request $request
     * @return Response
     */
    public function lists(Request $request)
    {
        $user = Auth::user();
        $roles = $user->roles;
        $roles = obj2arr($roles);
        $roleArr = array_column($roles,'id','name');
        if(array_key_exists(env('ROOT_KEY'),$roleArr)){
            $menus = $this->menuRepository->scopeQuery(function($query){
                return $query->orderBy('sort','asc');
            })->all();
        } else {
            $menus = DB::table("menu")
                ->leftjoin("role_has_menu", "role_has_menu.menu_id",'=','menu.id')
                ->whereIn("role_has_menu.role_id",$roleArr)
                ->orderBy("sort", 'asc')
                ->get();
        }
        $menus = obj2arr($menus);
        $menus = make_tree($menus, 'id', 'pid', '_child', 0);
        return $this->sendResponse($menus, '查询成功');
    }



    /**
     * Store a newly created User in storage.
     * POST /menus
     *
     * @param CreateUserAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateMenuAPIRequest $request)
    {
        $input = $request->all();
        $menus = $this->menuRepository->create($input);
        $menus->save();

        if($menus->id) {
            $user = Auth::user();
            $roles = $user->roles;
            $roles = obj2arr($roles);
            $roleArr = array_column($roles, 'id', 'name');
            foreach ($roleArr as $v) {
                $tmp = DB::table("role_has_menu")->where("role_id",$v)->where("menu_id",$menus->id)->first();
                if(empty($tmp)){
                    $f = DB::table("role_has_menu")->insert(["role_id"=>$v,"menu_id"=>$menus->id]);
                }
            }
        }
        return $this->sendResponse($menus->toArray(), '添加菜单成功');
    }

    /**
     * 获取用户详情
     * GET|HEAD /menus/{id}
     *
     * @param $id
     * @param Request $request
     * @return mixed
     */
    public function show($id, Request $request)
    {
        $this->menuRepository->pushCriteria(new RequestCriteria($request));
        $menu = $this->menuRepository->findWithoutFail($id);

        if (empty($menu)) {
            return $this->sendError('Menu not found');
        }

        return $this->sendResponse($menu->toArray(), '查询菜单成功');
    }

    /**
     * Update the specified Menu in storage.
     * PUT/PATCH /menus/{id}
     *
     * @param  int $id
     * @param UpdateMenuAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateMenuAPIRequest $request)
    {
        $input = $request->all();

        $menu = $this->menuRepository->findWithoutFail($id);

        if (empty($menu)) {
            return $this->sendError('菜单不存在');
        }

        $menu = $this->menuRepository->update($input, $id);

        return $this->sendResponse($menu->toArray(), '修改菜单成功');
    }

    /**
     * Remove the specified Menu from storage.
     * DELETE /menus/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $res = $this->getBelongIds([$id]);
        $res[] = $id;
        $menu = $this->menuRepository->findWithoutFail($id);
        if (empty($menu)) {
            return $this->sendError('菜单不存在');
        }
        foreach ($res as $v) {
            $this->menuRepository->deleteWhere(['id'=>$v]);
        }
        return $this->sendResponse($id, '菜单删除成功');
    }


}
